#include <my_head.h>

int main(int argc, const char *argv[]){
    if(4 != argc){
        printf("Usage : %s <multi_IP> <local_IP> <PORT>\n", argv[0]);
        return -1;
    }
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(-1 == sockfd)
        ERR_LOG("socket error");
    // 填充组播结构体
    struct sockaddr_in serveraddr;
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(atoi(argv[3]));
    // 要填多播组的IP地址  224.0.0.1-239.255.255.254
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    socklen_t serveraddr_len = sizeof(serveraddr);

    if(-1 == bind(sockfd, (struct sockaddr *)&serveraddr, serveraddr_len))
        ERR_LOG("bind error");
    
    // 设置加入多播组
    struct ip_mreqn mreqn;
    mreqn.imr_multiaddr.s_addr = inet_addr(argv[1]);
    mreqn.imr_address.s_addr = inet_addr(argv[2]);
    mreqn.imr_ifindex = 0;
    if(-1 == setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreqn, sizeof(mreqn)))
        ERR_LOG("setsockopt error");

    struct sockaddr_in clientaddr;
    socklen_t clientaddr_len = sizeof(clientaddr);

    char buff[128] = {0};
    while(1){
        if(-1 == recvfrom(sockfd, buff, sizeof(buff), 0, \
                (struct sockaddr *)&clientaddr, &clientaddr_len))
            ERR_LOG("recvfrom error");
        printf("收到[%s:%d]发来的数据[%s]\n", \
            inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port), buff);
        // 由于广播是一个发送方对应多个接收方的 所以接收方这里就不给发送方回复应答消息了
    }
    close(sockfd);

    return 0;
}